package com.hrt.manage.cash.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.base.BaseController;
import com.hrt.bean.Cash;
import com.hrt.bean.UserVO;
import com.hrt.bean.UsersInfor;
import com.hrt.manage.cash.service.CashService;
import com.hrt.util.PageUtils;
import com.hrt.util.WebParams;
import com.hrt.util.upload.Plupload;
import com.hrt.util.upload.UploadUtil;

@Controller
@RequestMapping("/manage/cash")
public class CashController extends BaseController<Cash> {

	private List<Long> cashNums;

	@Autowired
	private CashService service;

	private Cash cash;

	private String FileDir = "uploadfile/";

	// @Autowired
	// private OcrTools ocrTools;

	@Autowired
	private UploadUtil uploadUtil;

	private Long cashNum;

	@RequestMapping(value = "/list")
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		List<Cash> cashList = new ArrayList<Cash>();
		view.setViewName("manage/cash/list");
		cashList = service.queryByPage(getPageIndex(), getPageSize());
		setList(cashList);
		setTotalCount(service.totalCount(null));
		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();
		view.addObject("cashNums", getCashNums());
		view.addObject("pageResult", page);

		return view;
	}

	public List<Long> getCashNums() {
		if (cashNums == null) {
			cashNums = new ArrayList<Long>();
			cashNums.add(new Long(5));
			cashNums.add(new Long(10));
			cashNums.add(new Long(20));
			cashNums.add(new Long(50));
			cashNums.add(new Long(100));
		}

		return cashNums;
	}

	@RequestMapping(value = "/add")
	@ResponseBody
	public Map<String, Object> add(HttpServletRequest request,
			HttpServletResponse response) {
		cash = new Cash();

		Map<String, Object> map = BaseController.transBean2Map(cash);

		return map;

	}

	@SuppressWarnings("unused")
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public void upload(Plupload plupload, HttpServletRequest request,
			HttpServletResponse response) {
		System.out.println(plupload.getChunk() + "===" + plupload.getName()
				+ "---" + plupload.getChunks());

		plupload.setRequest(request);
		// 文件存储路径
		File dir = new File(plupload.getRequest().getSession()
				.getServletContext().getRealPath("/")
				+ FileDir);

		System.out.println(dir.getPath());

		try {
			// 上传文件
			File file = uploadUtil.upload(plupload, dir);
			// 判断文件是否上传成功（被分成块的文件是否全部上传完成）
			System.out.println(file.getAbsoluteFile().getAbsolutePath());
			response.setContentType("application/json");
			if (file != null) {
				System.out.println(plupload.getName() + "----");
				String fileFullPath = "http://127.0.0.1:8080"
						+ request.getContextPath() + "/" + FileDir
						+ plupload.getName();
				System.out.println("----------------" + fileFullPath);
				/**
				 * 写数据库
				 */

				String subfix = new String();
				// if(file.getName().indexOf(".")!=-1){
				// subfix =
				// plupload.getName().substring(plupload.getName().indexOf(".")+1);
				// }
				// String text=ocrTools.recognizeText(file, subfix);
				// System.out.println("----------------" + text);
				String UPLOAD_SUCCESS = WebParams.DO_MAIN
						+ request.getContextPath() + "/" + FileDir
						+ file.getName();
				// UPLOAD_SUCCESS=fileFullPath;

				System.out.println("----------------" + UPLOAD_SUCCESS);
				byte[] responseBytes = UPLOAD_SUCCESS.getBytes();
				response.setContentLength(responseBytes.length);
				ServletOutputStream pw = response.getOutputStream();
				pw.write(responseBytes);
				pw.flush();
				pw.close();

			} else {
				String UPLOAD_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";

				response.setContentType("application/json");
				final byte[] responseBytes = UPLOAD_ERROR.getBytes();
				response.setContentLength(responseBytes.length);
				final ServletOutputStream pw = response.getOutputStream();
				pw.write(responseBytes);
				pw.flush();
				pw.close();
			}

		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			String UPLOAD_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";

			response.setContentType("application/json");
			byte[] responseBytes = UPLOAD_ERROR.getBytes();
			response.setContentLength(responseBytes.length);
			try {
				ServletOutputStream pw = response.getOutputStream();
				pw.write(responseBytes);
				pw.flush();
				pw.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		} catch (IOException e) {
			String UPLOAD_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}";

			response.setContentType("application/json");
			byte[] responseBytes = UPLOAD_ERROR.getBytes();
			response.setContentLength(responseBytes.length);

			try {
				ServletOutputStream pw = response.getOutputStream();
				pw.write(responseBytes);
				pw.flush();
				pw.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public void save(@ModelAttribute("cashDetail") Cash cash,
			HttpServletRequest request, HttpServletResponse response) {
		ModelAndView model = new ModelAndView();
		System.out.println("save");

		System.out.println(cash.getImgUrl());
		System.out.println(cash.getDescription());
		System.out.println(cash.getStatus());
		UserVO manager = this.getOnlineManager(request, response);
		cash.setCreator(manager.getLoinName());
		cash.setCreateTime(service.getDate());
		cash.setEditor(manager.getLoinName());
		cash.setEditTime(this.service.getDate());

		try {

			this.service.saveCash(cash);

			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/show")
	@ResponseBody
	public Map show(@RequestParam(value = "id", required = true) Long cashId,
			HttpServletRequest request, HttpServletResponse response) {

		Map map = new HashMap();
		if (cashId != null && !"".equals(cashId)) {
			// Map resultMap=new HashMap<K, V>();
			System.out.println("showshowshowshowshow " + cashId);
			cash = service.getCashByid(cashId);
			if (cash != null) {
				map = transBean2Map(cash);

			}

		}
		return map;

	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public void update(@ModelAttribute("cashDetail") Cash ca,
			HttpServletRequest request, HttpServletResponse response) {

		System.out.println("update");

		try {
			this.cash = service.getCashByid(ca.getId());
			this.cash.setCashCode(ca.getCashCode());
			cash.setDescription(ca.getDescription());
			cash.setIsdelete(0);
			cash.setImgUrl(ca.getImgUrl());
			cash.setNote(ca.getNote());
			cash.setNum(ca.getNum());
			cash.setStatus(ca.getStatus());
			
			UserVO manager = this.getOnlineManager(request, response);

			if (manager != null) {
				this.cash.setEditor(manager.getLoinName());
				this.cash.setEditTime(service.getDate());
			}

			service.udateCash(cash);
			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	
	@RequestMapping(value = "/confirm", method = RequestMethod.POST)
	public void confirm(@ModelAttribute("cashDetail") Cash ca,
			HttpServletRequest request, HttpServletResponse response) {
		
		System.out.println("confirm");

		try {
			cash = service.getCashByid(ca.getId());
			cash.setCashCode(ca.getCashCode());
			cash.setDescription(ca.getDescription());
			cash.setIsdelete(0);
			cash.setImgUrl(ca.getImgUrl());
			cash.setNote(ca.getNote());
			cash.setNum(ca.getNum());
			cash.setStatus(ca.getStatus());
			
			UserVO manager = this.getOnlineManager(request, response);

			if (manager != null) {
				this.cash.setEditor(manager.getLoinName());
				this.cash.setEditTime(service.getDate());
			}
			cash.setStatus(new Integer(1));
			service.udateCash(cash);
			response.sendRedirect("list.do");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}


	@RequestMapping(value = "/queryByPage")
	@ResponseBody
	public Map<String, PageUtils<Cash>> queryByPage(
			@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
			@RequestParam(value = "pageSize", required = false) Integer pageSize,
			@RequestParam(value = "cashNum", required = false) Long cashNum,
			HttpServletRequest request) {
		Map<String, PageUtils<Cash>> resultMap = new HashMap<String, PageUtils<Cash>>();

		if (pageSize == null || "".equals(pageSize)) {
			pageSize = 30;
		}
		if (pageIndex == null || "".equals(pageIndex)) {
			pageIndex = 1;
		}
		setPageIndex(pageIndex);

		setPageSize(pageSize);
		List<Map<String, Object>> conditions = new ArrayList<Map<String, Object>>();
		List<Cash> resultList = new ArrayList<Cash>();
		setTotalCount(this.service.totalCount(null));
		this.cashNum = cashNum;
		if (this.cashNum == null || this.cashNum == -1) {
			resultList = service.queryByPage(getPageIndex(), getPageSize());
		} else {
			resultList = service.queryByPage(conditions, pageIndex, pageSize);
		}
		setList(resultList);

		this.setPageCount(this.computePageCount(this.getTotalCount(),
				this.getPageSize()));

		page = this.getPage();

		resultMap.put("pageResult", page);
		return resultMap;
	}
	
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody Long[] delete(
			@RequestParam(value = "ids", required = true) String ids,
			HttpServletResponse response) throws IOException {
		Long[] idArr = null;
		ModelAndView view = new ModelAndView();

		if (ids != null) {
			if (ids.indexOf(",") != -1) {
				String[] idStrs = ids.split(",");
				idArr = new Long[idStrs.length];
				for (int idx = 0; idx < idStrs.length; idx++) {
					idArr[idx] = Long.parseLong(idStrs[idx]);
				}
			} else {
				idArr = new Long[] { Long.parseLong(ids) };
			}

		}
		try {
			Long[] delArr=this.service.deleteById(idArr);
			if(delArr.length==idArr.length){
				return delArr;
			}
			else{
				throw new Exception("delete failly");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

}
